package ext.csc.component.numbergen.utilities;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Vector;

import javax.servlet.jsp.PageContext;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;

public class FileUploader {
	public String filepath = "";
	public SmartUpload su = null;
	public int count = 0;
	
	public FileUploader(PageContext pageContext,String tempPath){
		try {		
			this.filepath = tempPath;
			su = new SmartUpload();		
			su.initialize(pageContext);			
			su.upload();			
			System.out.println("Uploading files to path " + tempPath + "...");
			count = su.save(tempPath);		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}		
	}
	
	public Vector getFilesPath(){
		Vector v = new Vector();
		for (int i=0;i<su.getFiles().getCount();i++){
			File file = su.getFiles().getFile(i);		
			if (file.isMissing()) continue;
			System.out.println("Adding file [" + filepath + "/" + file.getFileName() + "]");
			v.add(filepath + "/" + file.getFileName());
		}
		return v;
	}
	
	public Vector getFilesName(){
		Vector v = new Vector();
		for (int i=0;i<su.getFiles().getCount();i++){
			File file = su.getFiles().getFile(i);		
			if (file.isMissing()) continue;
			v.add(file.getFileName());
		}
		return v;
	}
	
	public InputStream getInputStream(int i){
		InputStream is = null;
		File file = su.getFiles().getFile(i);
		if(!file.isMissing()){
			String fpath = this.filepath + "/" + file.getFileName();
			try {
				is = new FileInputStream(fpath);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}			
		}
		return is;
	}

	public int getCount() {
		return count;
	}

	public String getFilepath() {
		return filepath;
	}
}
